<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '213px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(Object.values(val))
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
    },
    setOptions(value, names) {
      this.chart.setOption({
        backgroundColor: 'rgba(0,0,0,0)',
        grid: {
          top: 20,
          left: '2%',
          right: '2%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['在线总数', '设备总数', '激活总数', '解锁设备数']
        },
        yAxis: {
          type: 'value',
          splitLine: { show: false },
          splitArea: {
            show: false
          }
        },
        series: [
          {
            data: value,
            barWidth: 20,
            type: 'bar',
            itemStyle: {
              color: '#4A4DF0'
            },
          }
        ]
      })
    }
  }
}
</script>
